package com.qyhl.webtv.module_news.news.goodlife;


import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.MyListView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodLifeFragment extends BaseFragment implements GoodLifeContract.GoodLifeView {
    @BindView(R2.id.banner)
    SimpleBannerView banner;
    @BindView(R2.id.goods)
    TextView goods;
    @BindView(R2.id.play)
    TextView play;
    @BindView(R2.id.value)
    TextView value;
    @BindView(R2.id.header_layout)
    LinearLayout headerLayout;
    @BindView(R2.id.listview)
    MyListView listview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.list_mask)
    LoadingLayout listMask;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.scrollview)
    ScrollView scrollview;

    private GoodLifePresenter mPresenter;
    private List<NewsBean> mList;
    private List<NewsBean> headList;
    private RequestOptions options;
    private View view;


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.news_fragment_good_life, null);
    }

    @Override
    public void initImmersionBar() {
    }

    @Override
    protected void create() {
        mPresenter = new GoodLifePresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getHeaderData();
        mPresenter.getBodyData();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        mList = new ArrayList<>();
        headList = new ArrayList<>();

        //设置刷新控件
        refresh.setEnableLoadMore(false);
        refresh.setRefreshHeader(new MaterialHeader(getActivity()));
        refresh.setDisableContentWhenRefresh(true);

        //点击水波纹效果
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            goods.setBackgroundResource(R.drawable.news_center_item_ripple);
            value.setBackgroundResource(R.drawable.news_center_item_ripple);
            play.setBackgroundResource(R.drawable.news_center_item_ripple);
        }

        //glide 配置
        options = new RequestOptions()
                .placeholder(R.drawable.cover_large_default)
                .error(R.drawable.cover_large_default)
                .priority(Priority.HIGH);


        listview.setAdapter(new CommonAdapter<NewsBean>(getActivity(), R.layout.news_item_glife_list, mList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                TextView summary = viewHolder.getView(R.id.summary);
                ImageView cover = viewHolder.getView(R.id.cover);

                title.setText(item.getTitle());

                if (StringUtils.isNotEmpty(item.getSummary())) {
                    summary.setVisibility(View.VISIBLE);
                    summary.setText(item.getSummary());
                } else {
                    summary.setVisibility(View.GONE);
                }

                Glide.with(getActivity())
                        .load(item.getLogo())
                        .apply(options)
                        .into(cover);
            }
        });

        scrollview.scrollTo(0, 0);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //轮播监听
        banner.setOnItemClickListener(position -> {
            Bundle bundle = new Bundle();
            bundle.putString("newsId", headList.get(position).getID());
            RouterManager.router(ARouterPathConstant.GOOD_LIFE_DETAIL,bundle);

        });

        //刷新监听
        refresh.setOnRefreshListener(refreshlayout -> {
            mPresenter.getHeaderData();
            mPresenter.getBodyData();
        });

        //列表刷新
        listMask.setOnReloadListener(v -> {
            listMask.setReloadButtonText("加载中...");
            mPresenter.getBodyData();
        });

        //页面刷新
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getHeaderData();
            mPresenter.getBodyData();
        });

        //子栏目监听
        goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE,ActionConstant.HOME,ActionConstant.GOODLIFE);
                Bundle bundle = new Bundle();
                bundle.putString("id", "9836");
                bundle.putString("title", "趣物");
                RouterManager.router(ARouterPathConstant.GLIFE_LIST,bundle);

            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE,ActionConstant.HOME,ActionConstant.GOODLIFE);
                Bundle bundle = new Bundle();
                bundle.putString("id", "9837");
                bundle.putString("title", "汇生活");
                RouterManager.router(ARouterPathConstant.GLIFE_LIST,bundle);
            }
        });

        value.setOnClickListener(v -> {
            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE,ActionConstant.HOME,ActionConstant.GOODLIFE);
            Bundle bundle = new Bundle();
            bundle.putString("id", "9838");
            bundle.putString("title", "新知");
            RouterManager.router(ARouterPathConstant.GLIFE_LIST,bundle);
        });

        listview.setOnItemClickListener((parent, view, position, id) -> {
            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE,ActionConstant.HOME,ActionConstant.GOODLIFE);

            Bundle bundle = new Bundle();
            bundle.putString("newsId", mList.get(position).getID());
            RouterManager.router(ARouterPathConstant.GOOD_LIFE_DETAIL,bundle,R.anim.open_next,R.anim.close_main);

        });
    }


    @Override
    public void headError() {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        banner.setVisibility(View.GONE);
    }

    @Override
    public void headSuccess(List<NewsBean> beanList) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        headList.clear();
        headList.addAll(beanList);
        try {
            if (headList != null && beanList.size() > 0 && StringUtils.isNotEmpty(headList.get(0).getID())) {
                banner.setVisibility(View.VISIBLE);
            } else {
                banner.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            banner.setVisibility(View.GONE);
            return;
        }

        List<String> titleNames = new ArrayList<>();
        for (int i = 0; i < headList.size(); i++) {
            titleNames.add(headList.get(i).getTitle());
        }
        String[] titleStrings = new String[titleNames.size()];
        titleNames.toArray(titleStrings);
        //当只有一张轮播时
        if (headList.size() == 1) {
            banner.setCanLoop(false);
            banner.setTextBanner(titleStrings[0]);
        } else {
            banner.setCanLoop(true);
        }

        //初始化轮播信息
        banner.setPages(new SimpleHolderCreator() {
            @Override
            public Object createHolder() {
                return new BannerViewHolder();
            }
        }, headList).startTurning(3000)
                .setPageIndicator(new int[]{R.drawable.news_banner_indicator_off, R.drawable.news_banner_indicator_on}, titleStrings)
                .setPageIndicatorAlign(SimpleBannerView.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
    }


    @Override
    public void bodyError(String msg) {
        refresh.finishRefresh();
        listMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        listMask.setStatus(LoadingLayout.Error);
        listMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void bodyEmpty(String msg) {
        refresh.finishRefresh();
        listMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        listMask.setStatus(LoadingLayout.Empty);
        listMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void bodyNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.Success);
        listMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
        listMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void bodySuccess(List<NewsBean> beanList) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        listMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        listMask.setReloadButtonText("点击重试~~");

        mList.clear();
        mList.addAll(beanList);
    }

    public static GoodLifeFragment newInstance() {
        return new GoodLifeFragment();
    }

    /**
     * 轮播holder
     */
    class BannerViewHolder implements SimpleHolder<NewsBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, NewsBean data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getLogo())
                    .apply(options)
                    .into(imageView);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("新趣汇首页");
        MobclickAgent.onResume(getActivity());
    }


    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("新趣汇首页");
        MobclickAgent.onPause(getActivity());
    }
}
